<?php
/**
 * User: Titan
 * Date: Oct 22, 2010
 * Time: 3:41:20 PM
 * 
 * This file handles the output display and content organization of all the /feature pages.
 * 
 * This file also includes the forms and tables for those pages
 *
 * 
 */
 
$main = 'feature';

/**
 * feature()
 * 
 * this function is called immediately after all variables have been loaded and all forms
 * have been validated and submitted
 * 
 * @param mixed $vars
 * @return void
 */
function feature(&$vars)
{
	system_add_styles('assets/css/style.css');
	system_add_js('assets/js/jquery.js');
	
	$breadcrumbs = array(
		'Home' => array(
			'#title' => 'Home',
			'#anchor' => 'Home',
			'#attributes' => array(
				'class' => 'breadcrumb'
			),
			'#href' => base_path()
		)
	);
	
	if (!isset($GLOBALS['op']))
	{
		system_add_js('assets/js/selectable.table.js');
		system_page_title('Features');
	} 
	else
	{
		$breadcrumbs['Features'] = array(
			'#title' => 'Features',
			'#anchor' => 'Features',
			'#attributes' => array(
				'class' => 'breadcrumb'
			),
			'#href' => base_path() . 'feature'
		);
		
		system_page_title(ucwords($GLOBALS['op']) . ' Features');
	}
	
	system_breadcrumbs($breadcrumbs);
}

/**
 * feature_prerender_page()
 * 
 * this function sets the content variable for the page.tpl.php template and any other data
 * such as page titles, etc.
 * 
 * This function also chooses which forms to display based on query string parameters
 * (ie. ?op=edit or ?op=add, etc.)
 * 
 * @param mixed $vars
 * @return void
 */
function feature_prerender_page(&$vars)
{
	global $feature_form, $feature_table, $op, $subop;
	
	$output = '';
	switch ($op)
	{
		case 'add':
		case 'edit':
		case 'clone':
		case 'delete':
			if (isset($vars['query']['fid']))
			{
				if (!isset($feature_form))
				{
					if ($op != 'delete')
					{
						feature_edit_form($vars['query']['fid']);
					}
					else
					{
						feature_delete_confirmation_form($vars['query']['fid']);
					}
				}
				
				$output = form_build($feature_form, 'feature_view_' . $op);
				system_page_title(ucwords($GLOBALS['op']) . ' Features');
			}
			else 
			{
				system_redirect(base_path() . 'feature');
			}
			
			break;
		default: 
			if (!isset($feature_form))
			{
				$feature_form = feature_default_form();
			}
			
			if (!isset($feature_table))
			{
				$feature_table = feature_default_table();
			}
			
			$add_button = array(
				'#type' => 'button',
				'#value' => 'add',
				'#id' => render_unique_id('add-feature'),
				'#attributes' => array(
					'class' => 'ui-button add form-submit',
					'onclick' => "window.location = '" . base_path() . "feature?op=add&fid=0';"
				),
				'#title' => '+ Add Feature',
				'#prefix' => '<div class="form-item form-submit">',
				'#suffix' => '</div>'
			);
				
			if (isset($subop) && $subop == 'search')
			{
				system_page_title('Search Features');
				$reset_button = array(
					'#type' => 'button',
					'#value' => 'clear',
					'#id' => render_unique_id('clear-search'),
					'#attributes' => array(
						'class' => 'ui-button clear form-submit',
						'onclick' => "window.location = '" . base_path() . "feature';"
					),
					'#title' => 'Clear Search',
					'#prefix' => '<div class="form-item form-submit">',
					'#suffix' => '</div>'
				);
			}
			else
			{
				system_page_title('Features');
			}
			
			$form_output = render('generic_button', $add_button) . (isset($reset_button) ? render('generic_button', $reset_button) : '') . form_build($feature_form, 'feature_view' . (empty($op) ? '' : '_' . $op));
			
			$output .= $form_output . render('table', $feature_table);
			
			break;
	}
	
	$vars['content'] = $output;
}

/**
 * feature_default_table()
 * 
 * This function returns the default table for the page (ie. the table that is rendered) with no 
 * query string parameters
 * 
 * @return
 */
function feature_default_table()
{
	$result = db_query('SELECT * FROM feature WHERE fid > 0 ORDER BY description');
	
	$headers = array('', 'Description', 'Details');

	$edit_link =  array(
		'#anchor' => 'Edit',
		'#attributes' => array(
			'class' => 'action-link edit'
		),
		'#title' => 'Edit'
	);
	
	$rows = array();
	while ($feature = db_fetch_array($result))
	{
		$link = $edit_link;
		$link['#href'] = base_path() . 'feature?op=edit&fid=' . $feature['fid'];
		$rows[] = array(
			'#cells' => array(
				'edit' => a($link),
				'description' => $feature['description'],
				'details' => $feature['details']
			)
		);
	}
	
	if (empty($rows))
	{
		$rows[] = array(
			'#cells' => array(
				'no_results' => array(
					'#value' => '<h2 style="text-align:center;">Your search returned no results.</h2>',
					'#attributes' => array(
						'colspan' => count($headers)
					)
				)
			)
		);
	}
	
	$table_id = render_unique_id('feature-table');
	$feature_table = array(
		'#attributes' => array(
			'id' => $table_id,
			'border' => 1,
			'cellspacing' => 0,
			'cellpadding' => 8,
			'class' => 'selectable data-list-table'
		),
		'#header' => $headers,
		'#rows' => $rows
	);
	
	return $feature_table;
}

/**
 * feature_default_form()
 * 
 * This function returns the default form for the page (ie. the form that is rendered) with no 
 * query string parameters
 * 
 * in this case, the default form is a search form that allows searching on a feature's fields
 * 
 * @return
 */
function feature_default_form()
{
	$form_id = render_unique_id('feature-default-view');
	$form = array(
		'#id' => $form_id,
		'#action' => base_path() . 'feature?op=view&subop=search',
		'#method' => 'POST',
		'#callback' => 'feature_search_submit',
		'#attributes' => array(
			'class' => 'container-inline search-form'
		),
		'#inputs' => array(
			'description' => array(
				'#type' => 'textfield',
				'#id' => render_unique_id('filter-description'),
				'#title' => 'Description',
				'#size' => 45
			),
			'search_wrapper' => array(
				'#type' => 'html',
				'#value' => '<div class="form-item-wrapper search">'
			),
			'search' => array(
				'#type' => 'submit',
				'#value' => 'Search',
				'#id' => render_unique_id('search'),
				'#attributes' => array(
					'class' => 'ui-button search',
					'onclick' => "$('#" . $form_id . "').get(0).setAttribute('action', '" . base_path() . "feature?op=view&subop=search');"
				)
			),
			'search_wrapper_close' => array(
				'#type' => 'html',
				'#value' => '</div>'
			)
		)
	);
	
	return $form;
}

/**
 * feature_edit_form()
 * 
 * This is the form that is rendered when editing or adding a feature
 * 
 * @param mixed $fid
 * @param mixed $values
 * @return void
 */
function feature_edit_form($fid, $values = array())
{
	global $feature_form, $op;
	
	if (!empty($values))
	{
		$feature = new Feature(
			array(
				'description' => $values['description'], 
				'details' => $values['details'],
				'fid' => $fid
			)
		);
	}
	else if (!empty($fid))
	{
		$feature = new Feature($fid);
	}
	else
	{
		$feature = new Feature();
	}
	
	$inputs = array();	
	$form_id = render_unique_id('feature-edit-' . $fid);
	
	$inputs['description'] = array(
		'#type' => 'textfield',
		'#id' => render_unique_id('edit-description'),
		'#title' => 'Description',
		'#value' => $feature->description,
		'#size' => 60
	);
	$inputs['details'] = array(
		'#type' => 'textarea',
		'#id' => render_unique_id('edit-details'),
		'#title' => 'Details', 
		'#rows' => 5,
		'#cols' => 60,
		'#value' => $feature->details
	);
	$inputs['button_wrapper'] = array(
		'#type' => 'html',
		'#value' => '<div class="form-item-wrapper">'
	);
	$inputs['cancel'] = array(
		'#type' => 'submit',
		'#value' => 'Cancel',
		'#id' => render_unique_id('cancel'),
		'#attributes' => array(
			'class' => 'ui-button',
		)
	);
	
	if ($op == 'edit')
	{
		$inputs['cancel']['#attributes']['onclick'] = "$('#" . $form_id . "').get(0).setAttribute('action', '" . base_path() . "feature?op=edit&fid=" . $feature->fid . "');";
		$inputs['delete'] = array(
			'#type' => 'submit',
			'#value' => 'Delete',
			'#id' => render_unique_id('delete'),
			'#attributes' => array(
				'class' => 'ui-button',
				'onclick' => "$('#" . $form_id . "').get(0).setAttribute('action', '" . base_path() . "feature?op=delete&subop=confirm&fid=" . $feature->fid . "');"
			)
		);
		$inputs['save'] = array(
			'#type' => 'submit',
			'#value' => 'Save',
			'#id' => render_unique_id('save'),
			'#attributes' => array(
				'class' => 'ui-button',
				'onclick' => "$('#" . $form_id . "').get(0).setAttribute('action', '" . base_path() . "feature?op=edit&subop=save&fid=" . $feature->fid . "');"
			)
		);
	}
	else if ($op == 'add')
	{
		$inputs['cancel']['#attributes']['onclick'] = "$('#" . $form_id . "').get(0).setAttribute('action', '" . base_path() . "feature');";
		$inputs['save'] = array(
			'#type' => 'submit',
			'#value' => 'Save',
			'#id' => render_unique_id('save'),
			'#attributes' => array(
				'class' => 'ui-button',
				'onclick' => "$('#" . $form_id . "').get(0).setAttribute('action', '" . base_path() . "feature?op=add&subop=save&fid=" . $feature->fid . "');"
			)
		);
	}
	
	$inputs['button_wrapper_close'] = array(
		'#type' => 'html',
		'#value' => '</div>'
	);
		
	$feature_form = array(
		'#id' => $form_id,
		'#action' => base_path() . 'feature?op=edit&subop=save&fid=' . $feature->fid,
		'#method' => 'POST',
		'#validator' => 'feature_edit_validate',
		'#callback' => 'feature_edit_submit',
		'#inputs' => $inputs, 
		'#description' => 'All fields are required.',
		'#attributes' => array(
			'class' => 'edit-feature'
		)
	);
}

/**
 * feature_edit_validate()
 * 
 * @param mixed $form_result
 * @return void
 */
function feature_edit_validate(&$form_result)
{
	$values = $form_result['values'];
	if ($values['submit'] == 'Save')
	{
		$feature = new Feature();
		
		$reload = FALSE;
		if (!isset($values['description']))
		{
			$reload = TRUE;
			form_error('description', 'You must specify a description.');
		}
		else 
		{
			if (strlen($values['description']) >= 255)
			{
				$reload = TRUE;
				form_error('description', 'The description must be less than 255 characters.');
			}
			
			if ($values['description'] == $feature->description)
			{
				$reload = TRUE;
				form_error('description', 'Please add a feature description.');
			}
		}
		
		if (!isset($values['details']))
		{
			$reload = TRUE;
			form_error('details', 'You must specify details.');
		}
		else if ($values['details'] == $feature->details)
		{
			$reload = TRUE;
			form_error('details', 'Please add feature details.');
		}
		
		if ($reload)
		{
			feature_edit_form($_GET['fid'], $form_result['values']);
		}
	}
}

/**
 * feature_edit_submit()
 * 
 * @param mixed $form_result
 * @return void
 */
function feature_edit_submit(&$form_result)
{
	$values = $form_result['values'];
	if ($values['submit'] == 'Save')
	{
		global $op;
		
		$feature = '';
		if ($op == 'edit')
		{
			$feature = new Feature($_GET['fid']);
		} 
		else if ($op = 'add')
		{
			$feature = new Feature();
		}
		
		$feature->description = $values['description'];
		$feature->details = $values['details'];
		
		$feature->save();
		
		system_redirect(base_path() . 'feature?op=edit&fid=' . $feature->fid);
	}
	else if ($values['submit'] == 'Delete')
	{
		
	}
	else
	{
		system_redirect(base_path() . 'feature');
	}
}

/**
 * feature_delete_confirmation_form()
 * 
 * @param mixed $fid
 * @return void
 */
function feature_delete_confirmation_form($fid)
{
	global $feature_form;
	
	$form_id = render_unique_id('feature-delete');
	$feature_form = array(
		'#id' => $form_id,
		'#action' => base_path() . 'feature?op=delete&fid=' . $fid,
		'#method' => 'POST',
		'#validator' => 'feature_delete_feature_confirmation_validate',
		'#callback' => 'feature_delete_feature_confirmation_submit',
		'#inputs' => array(
			'confirm' => array(
				'#title' => 'Are you sure you want to delete this feature?',
				'#type' => 'checkbox',
				'#description' => 'This feature will be completely erased from the system.',
				'#value' => 1,
				'#checked' => FALSE
			),
			'submit' => array(
				'#type' => 'submit',
				'#value' => 'Delete',
				'#attributes' => array(
					'onclick' => "$('#" . $form_id . "').get(0).setAttribute('action', '" . base_path() . "feature?op=delete&fid=" . $fid . "');"
				)
			),
			'cancel' => array(
				'#type' => 'submit',
				'#value' => 'Cancel',
				'#attributes' => array(
					'onclick' => "$('#" . $form_id . "').get(0).setAttribute('action', '" . base_path() . "feature?op=delete&subop=cancel&fid=" . $fid . "');"
				)
			)
		)
	);
	
	if ($error = form_error('confirm'))
	{
		$feature_form['#inputs']['confirm']['#attributes'] = array('class' => 'error');
		system_set_message($error, 'error');
	}
}

/**
 * feature_delete_feature_confirmation_validate()
 * 
 * @param mixed $form_result
 * @return void
 */
function feature_delete_feature_confirmation_validate(&$form_result)
{
	switch ($form_result['values']['submit']) 
	{
		case 'Delete':
			$confirmation_form = FALSE;
			if (!isset($form_result['values']['confirm']) || $form_result['values']['confirm'] != 1)
			{
				form_error('confirm', 'Please confirm that you would like to delete this feature, or click Cancel.');
				$confirmation_form = TRUE;
			}
			
			if ($confirmation_form)
			{
				front_delete_developer_confirmation_form($form_result['values']);
			}
			
			break;
		case 'Cancel':
			
			break;
	}
}

/**
 * feature_delete_feature_confirmation_submit()
 * 
 * @param mixed $form_result
 * @return void
 */
function feature_delete_feature_confirmation_submit(&$form_result)
{
	if ($form_result['values']['submit'] == 'Delete')
	{
		if (isset($_GET['fid']))
		{
			$description = db_result(db_query('SELECT description FROM feature WHERE fid=%d', $_GET['fid']));
			
			$description = db_query('DELETE FROM feature WHERE fid=%d', $_GET['fid']);
			$relational_result = db_query('UPDATE task SET fid=0 WHERE fid=%d', $_GET['fid']);
			if ($description && $relational_result)
			{
				system_set_message('The following feature was successfully deleted: <code>' . $description . '</code>');
				system_redirect(base_path() . 'feature');
			}
		}
	}
	else
	{
		system_redirect(base_path() . 'feature?op=edit&fid=' . $_GET['fid']);
	}
}

/**
 * feature_search_submit()
 * 
 * @param mixed $form_result
 * @return void
 */
function feature_search_submit(&$form_result)
{
	global $feature_table, $feature_form;
	
	$values = $form_result['values'];
	
	$feature_form = feature_default_form();
	
	$feature_form['#inputs']['description']['#value'] = (isset($values['description']) ? $values['description'] : '');
	
	$result = db_query("SELECT * FROM feature WHERE fid > 0 AND description LIKE '%%%s%%' ORDER BY description", $values['description']);
	
	$headers = array('', 'Description', 'Details');
	$rows = array();
	while ($feature = db_fetch_array($result))
	{
		$rows[] = array(
			'#cells' => array(
				'edit' => a(
					array(
						'#anchor' => 'Edit',
						'#attributes' => array(
							'class' => 'action-link edit'
						),
						'#title' => 'Edit'
					)
				),
				'description' => $feature['description'],
				'details' => $feature['details']
			)
		);
	}
	
	if (empty($rows))
	{
		$rows[] = array(
			'#cells' => array(
				'no_results' => array(
					'#value' => '<h2 style="text-align:center;">Your search returned no results.</h2>',
					'#attributes' => array(
						'colspan' => count($headers)
					)
				)
			)
		);
	}
	
	$table_id = render_unique_id('feature-table');
	$feature_table = array(
		'#attributes' => array(
			'id' => $table_id,
			'border' => 1,
			'cellspacing' => 0,
			'cellpadding' => 8,
			'class' => 'selectable data-list-table'
		),
		'#header' => $headers,
		'#rows' => $rows
	);
}
